#!/bin/bash

if [[ $# -ne 2 ]]; then
    echo "The format is as follows:"
    echo "./q-e-6.6.sh buildpath installpath"
    echo ":param buildpath: 应用构建绝对路径"
    echo ":param installpath: 应用安装绝对路径"
    exit 1
fi

if [[ ! "$1" =~ ^/.* || ! -d "$1" || "$1" = "/" ]]; then echo "请输入正确的构建路径"; exit 1; fi
if [[ ! "$2" =~ ^/.* || ! -d "$2" || "$2" = "/" ]]; then echo "请输入正确的安装路径"; exit 1; fi

buildpath=$1
installpath=$2
[[ "$buildpath" =~ .*/$ ]] && buildpath=${buildpath%/*}
[[ "$installpath" =~ .*/$ ]] && installpath=${installpath%/*}
[[ "$buildpath" == "$installpath" ]] && echo "构建路径与安装路径需为不同路径" && exit 1

set -e
yum install -y wget tar environment-modules

wget -t 10 -c -P $buildpath https://github.com/QEF/q-e/archive/refs/tags/qe-6.6.tar.gz
tar xf $buildpath/qe-6.6.tar.gz -C $buildpath && rm -rf $buildpath/qe-6.6.tar.gz
cd $buildpath/q-e-qe-6.6
export BLAS_LIBS="-L$installpath/OPENBLAS/lib -lopenblas"
export LAPACK_LIBS="-L$installpath/OPENBLAS/lib -lopenblas"
export SCALAPACK_LIBS="-L$installpath/SCALAPACK -lscalapack"
export DEFS="__PGI"
./configure --prefix=$installpath/q-e-6.6 --enable-openmp ARCH=arm F77=flang F90=flang FC=flang CC=clang CFLAGS="-O3 -g -D__PGI -mcpu=native" FFLAGS="-O3 -g -D__PGI -mcpu=native" LDFLAGS="$LDFLAGS" MPIF90=mpifort MPIF77=mpifort CC=mpicc
sed -i "s|= gfortran|= flang|g" $(pwd)/make.inc
sed -i "s|= gfortran|= flang|g" $(pwd)/PlotPhon/SRC/make.inc
make -j$(nproc) all
make install
cat>"$installpath/q-e-6.6/q-e_modulefiles"<<EOF
#%Module1.0
conflict qe
variable modfile [file normalize [info script]]
proc getModulefileDir {} {
    variable modfile
    set modfile_path [file dirname \$modfile]
    return \$modfile_path
}
set pwd [getModulefileDir]
set qe \$pwd
setenv qe \$qe
prepend-path PATH \$qe/bin
EOF
export PATH=$installpath/q-e-6.6/bin:$PATH
